package com.ruoyi.project.drugs.controller;


import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ruoyi.project.system.domain.Order;
import com.ruoyi.project.system.service.ShopCardService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.TDrugs;
import com.ruoyi.project.system.domain.TNews;
import com.ruoyi.project.system.domain.TOrder;
import com.ruoyi.project.system.service.ITDrugsService;
import com.ruoyi.project.system.service.ITOrderService;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/drugs")
public class DrugsController extends BaseController {


    @Autowired
    private ITDrugsService tDrugsService;
    @Autowired
    private ITOrderService iTOrderService;
    @Autowired
    private ShopCardService shopCardService;
    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TDrugs tDrugs) {
        SecurityUtils.getLoginUser();
        if (SecurityUtils.getLoginUser().getUser().getRoles().get(0).getDataScope().equals("5")) {
            tDrugs.setIsShelves("1");
            tDrugs.setIsSelf("1");
        }
        startPage();
        tDrugs.setFlag("0");
        List<TDrugs> list = tDrugsService.selectTDrugsList(tDrugs);
        for (TDrugs td : list) {
            td.setDataScope(SecurityUtils.getLoginUser().getUser().getRoles().get(0).getDataScope());
        }
        return getDataTable(list);
    }

    @GetMapping("/getHome")
    public TableDataInfo getHome(TDrugs tDrugs) {
        startPage();
        tDrugs.setFlag("0");
        tDrugs.setIsShelves("1");
        List<TDrugs> list = tDrugsService.selectTDrugsList(tDrugs);
        return getDataTable(list);
    }

    /**
     * 新增【药品】
     */
    @Log(title = "【药品】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDrugs tDrugs) {
        tDrugs.setCreateUser(SecurityUtils.getLoginUser().getUser().getUserName());
        tDrugs.setCreateDate(new Date());
        tDrugs.setUpdateUser(SecurityUtils.getLoginUser().getUser().getUserName());
        tDrugs.setUpdateDate(new Date());
        return toAjax(tDrugsService.insertTDrugs(tDrugs));
    }

    /**
     * 上传图片
     *
     * @param photos
     * @param requset
     * @return
     */
    @PostMapping("/uploadDrugs")
    public AjaxResult upload(@RequestParam("file") MultipartFile photo, HttpServletRequest requset) {
        String realpath = "E:\\RuoYi-Vue\\ruoyi-ui\\src\\assets\\image";//容器的webapp目录下
        System.out.println("----图片上传路径：" + realpath);
        String img = "";
        try {

            if (photo.isEmpty()) ;//可能会有三个上传表单却不一定三个都进行上传，这样其他的就为空需要判断
            FileUtils.copyInputStreamToFile(photo.getInputStream(), new File(realpath + "/" + photo.getOriginalFilename()));
            img = photo.getOriginalFilename();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(img);
    }

    /**
     * 删除【请填写功能名称】
     */
    //@PreAuthorize("@ss.hasPermi('system:drugs:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tDrugsService.deleteTDrugsByIds(ids));
    }

    /**
     * 上下架
     *
     * @param ids
     * @param shelves
     * @return
     */
    @PostMapping("/updateIsShelves/{ids}")
    public AjaxResult updateIsShelves(@PathVariable Long[] ids, @RequestBody String shelves) {
        return toAjax(tDrugsService.updateTDrugsById(shelves, ids));

        //return AjaxResult.success("新增订单成功");
    }

    /**
     * 根据id查询药品
     *
     * @param ids
     * @return
     */
    @PostMapping("/queryDrugsIds")
    public TableDataInfo queryDrugsIds(@RequestBody Long[] ids) {
        startPage();
        List<TDrugs> list = tDrugsService.selectTDrugsListByIds(ids);
        return getDataTable(list);
    }

    /**
     * 新增订单
     *
     * @param tOrders
     * @return
     */
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody Order order) {
        System.out.print("请求参数输出"+order);
        List<TOrder> tOrders =order.gettOrder();
        for (int i = 0; i < tOrders.size(); i++) {
            tOrders.get(i).setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            tOrders.get(i).setCreateUser(SecurityUtils.getLoginUser().getUser().getUserName());
            tOrders.get(i).setUpdateUser(SecurityUtils.getLoginUser().getUser().getUserName());
            tOrders.get(i).setRemark(order.getRemark());
        }
         int row = iTOrderService.insertTOrderList(tOrders);
        if (row > 0) {
            for(TOrder t:tOrders) {
                Map<String,Object> map = new HashMap<>();
                map.put("shopCardId",t.getShopCardId());
                map.put("status","1");
                shopCardService.updateShopCardById(map);
            }
            return AjaxResult.success("新增订单成功");
        } else {
            return AjaxResult.error("新增订单失败");
        }

    }

    /**
     * 获取药品详情
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tDrugsService.selectTDrugsById(id));
    }

    /**
     * 修改药品
     */
    //@PreAuthorize("@ss.hasPermi('system:news:edit')")
    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDrugs tDrugs) {
        return toAjax(tDrugsService.updateTDrugs(tDrugs));
    }


}
